
//
//  PayViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/28.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "PayViewController.h"
#import "TopBackView.h"
#import "Common.h"
#import "RootViewController.h"
#import "InstroctionViewController.h"
#import "ServeViewController.h"
#import "PayFinishVC.h"


#import <Pingpp.h>
#define kUrlScheme      @"demoapp001" // 这个是你定义的 URL Scheme，支付宝、微信支付、银联和测试模式需要。
#define kUrlWX  @"wx5f0250600950a712"

@interface PayViewController ()

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic) NSInteger rowNumber;
@property (nonatomic) BOOL isAgree;

@end

@implementation PayViewController


- (instancetype)init

{
    self = [super init];
    if (self) {
        self.quoteid = [[NSString alloc]init];
        self.orderid = [[NSString alloc]init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _rowNumber = 0;
    self.dataArray = [NSMutableArray arrayWithObjects:@"支付宝支付",@"微信支付", nil];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"立即支付"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = GrayColor;

    
    [self initSubViews];

}

-(void)initSubViews
{
    UIView *payView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, cellHeight * 5)];
    payView.backgroundColor = WhiteColor;
    [self.view addSubview:payView];
    
    UIView *payV = [[UIView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, cellHeight)];
    payV.backgroundColor = headerBottomColor;
    [self.view addSubview:payV];
    
    UILabel *payStyleL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, screenWidth, cellHeight)];
    payStyleL.text = @"支付方式";
    payStyleL.textColor = BlackTitleColor;
    payStyleL.font = Font(14);
    [payV addSubview:payStyleL];
    
    UILabel *lineL1 = [self backLableWithFloat:cellHeight];
    [payView addSubview:lineL1];
    
    //微信
    UIButton *wxButton = [UIButton buttonWithType:UIButtonTypeCustom];
    wxButton.frame = CGRectMake(0, CGRectGetMaxY(lineL1.frame), screenWidth, cellHeight);
    [payView addSubview:wxButton];
    
    UIImageView *wxImg = [[UIImageView alloc]initWithFrame:CGRectMake(18, cellHeight/2.0 - 7.5, 15, 15)];
    wxImg.image = [UIImage imageNamed:@"pay_wx"];
    [wxButton addSubview:wxImg];
    
    UILabel *wxLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(wxImg.frame) + 10, 0, 200, cellHeight)];
    wxLabel.text = @"微信支付";
    wxLabel.font = Font(13);
    wxLabel.textColor = BlackTitleColor;
    [wxButton addSubview:wxLabel];
    
    UIImageView *wxSelectImg = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth - 30, cellHeight/2.0 - 7.5, 15, 15)];
    [wxButton addSubview:wxSelectImg];
    wxSelectImg.image = [UIImage imageNamed:@"pay_unselectd"];
    [wxButton addTarget:self action:@selector(wxButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    wxSelectImg.tag = 601;

    UILabel *lineL2 = [self backLableWithFloat:cellHeight * 2];
    [payView addSubview:lineL2];

    
    //支付宝
    UIButton *aliButton = [UIButton buttonWithType:UIButtonTypeCustom];
    aliButton.frame = CGRectMake(0, CGRectGetMaxY(lineL2.frame), screenWidth, cellHeight);
    [payView addSubview:aliButton];
    
    UIImageView *aliImg = [[UIImageView alloc]initWithFrame:CGRectMake(18, cellHeight/2.0 - 7.5, 15, 15)];
    aliImg.image = [UIImage imageNamed:@"pay_ali"];
    
    [aliButton addSubview:aliImg];
    
    UILabel *aliLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(aliImg.frame) + 10, 0, 200, cellHeight)];
    aliLabel.text = @"支付宝支付";
    aliLabel.font = Font(13);
    aliLabel.textColor = BlackTitleColor;
    [aliButton addSubview:aliLabel];
    
    UIImageView *aliSelectImg = [[UIImageView alloc]initWithFrame:CGRectMake(screenWidth - 30, cellHeight/2.0 - 7.5, 15, 15)];
    [aliButton addSubview:aliSelectImg];
    aliSelectImg.image = [UIImage imageNamed:@"pay_unselectd"];
    aliSelectImg.tag = 602;
    [aliButton addTarget:self action:@selector(aliButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *lineL3 = [self backLableWithFloat:cellHeight * 3];
    [payView addSubview:lineL3];
    
    
    [self backProtocolViewWithFloat:CGRectGetMaxY(lineL3.frame) andView:payView];
    
    
    UILabel *lineL4 = [self backLableWithFloat:cellHeight * 4];
    [payView addSubview:lineL4];
    //支付余款
     UILabel *lastPayL = [[UILabel alloc]initWithFrame:CGRectMake(screenWidth - 120, CGRectGetMaxY(lineL3.frame) + cellHeight, 100 * kWidth, cellHeight)];
    
    lastPayL.textColor = YellowColor;
    lastPayL.text = self.moneyString;
    lastPayL.font = [UIFont boldSystemFontOfSize:16 * kHeight];
    [payView addSubview:lastPayL];
    [lastPayL sizeToFit];
    lastPayL.frame = CGRectMake(screenWidth - 20 - lastPayL.frame.size.width, CGRectGetMaxY(lineL3.frame) + cellHeight, lastPayL.frame.size.width, cellHeight);
    
    
    UILabel *lastL = [[UILabel alloc]initWithFrame:CGRectMake( CGRectGetMinX(lastPayL.frame) - 200, CGRectGetMaxY(lineL3.frame) + cellHeight, 200, cellHeight)];
    lastL.text = @"支付金额";
    lastL.textAlignment = NSTextAlignmentRight;
    lastL.textColor = YellowColor;
    lastL.font = [UIFont boldSystemFontOfSize:16 * kHeight];
    [payView addSubview:lastL];

    
    
    
    UIButton *payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    payButton.frame = CGRectMake(18,CGRectGetMaxY(payView.frame) + 30, screenWidth - 36, Button_Height) ;
    [payButton setTitle:@"立即支付" forState:UIControlStateNormal];
    payButton.layer.cornerRadius = 5;
    [payButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [self.view addSubview:payButton];
    payButton.backgroundColor = YellowColor;
    [payButton addTarget:self action:@selector(payButtonAction) forControlEvents:UIControlEventTouchUpInside];
    payButton.titleLabel.font = Font(16);
}

-(void)backProtocolViewWithFloat:(CGFloat)y andView:(UIView *)view
{
    
    
    UIButton *agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    agreeButton.frame = CGRectMake(18, y + (cellHeight - 14.5)/2.0, 14.5, 14.5);
    agreeButton.tag = 400;
    [agreeButton setBackgroundImage:[UIImage imageNamed:@"regist_unselected"] forState:UIControlStateNormal];
    [agreeButton setBackgroundImage:[UIImage imageNamed:@"regist_selected"] forState:UIControlStateSelected];
    [agreeButton addTarget:self action:@selector(agreeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _isAgree = NO;
    
    
    [view addSubview:agreeButton];
    
    UILabel *agreeL = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(agreeButton.frame) + 8, y + (cellHeight - 20)/2.0 , 40 * kWidth, 20)];
    agreeL.text = @"已阅读";
    agreeL.textColor = littleBlackColor;
    agreeL.font = Font(12);
    [view addSubview:agreeL];
    
    UIButton *bigBut = [UIButton buttonWithType:UIButtonTypeCustom];
    bigBut.frame = CGRectMake(CGRectGetMinX(agreeButton.frame), CGRectGetMinY(agreeButton.frame) - 10, 75, Button_Height);
    [view addSubview:bigBut];
    [bigBut addTarget:self action:@selector(bigBut) forControlEvents:UIControlEventTouchUpInside];

    
    //运输说明按钮
    UIButton *transButton = [self backButtonWithString:@"《运输说明》" andFont:12 andFrame:CGRectMake(CGRectGetMaxX(agreeL.frame), y, 75 *kWidth, cellHeight)];
    [transButton addTarget:self action:@selector(transButton) forControlEvents:UIControlEventTouchUpInside];
    [transButton.titleLabel sizeToFit];
    transButton.frame = CGRectMake(CGRectGetMaxX(agreeL.frame), y, transButton.titleLabel.frame.size.width, cellHeight);
    [view addSubview:transButton];
    
    //车辆运输服务协议
    
    UIButton *backButton = [self backButtonWithString:@"《车辆运输服务协议》" andFont:12 andFrame:CGRectMake(CGRectGetMaxX(transButton.frame),y, 120 * kWidth, cellHeight)];
    [backButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    [backButton.titleLabel sizeToFit];
    backButton.frame = CGRectMake(CGRectGetMaxX(transButton.frame),y, backButton.titleLabel.frame.size.width, cellHeight);
    
    [view addSubview:backButton];
    
//    //服务协议
//    
//    UIButton *protocolButton = [self backButtonWithString:@"《服务协议》" andFont:12 andFrame:CGRectMake(CGRectGetMaxX(backButton.frame), y, 75 * kWidth, cellHeight)];
//    [protocolButton addTarget:self action:@selector(protocolButton) forControlEvents:UIControlEventTouchUpInside];
//    [view addSubview:protocolButton];
    
    
}


-(UILabel *)backLableWithFloat:(CGFloat )y{
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, y, screenWidth, 0.5)];
    label.backgroundColor = LineGrayColor;
    
    return label;
    
}

-(void)bigBut
{
    UIButton *button = (UIButton *)[self.view viewWithTag:400];
    [self agreeButtonAction:button];
}

//方框

-(void)agreeButtonAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        _isAgree = YES;
    } else {
        _isAgree = NO;
    }

}
//运输

-(void)transButton
{
    //运输说明
    InstroctionViewController *instroctionVC = [[InstroctionViewController alloc]init];
    [self.navigationController pushViewController:instroctionVC animated:YES];
}

//服务

-(void)backButton
{
    //服务
    ServeViewController *serveVC = [[ServeViewController alloc]init];
    
    [self.navigationController pushViewController:serveVC animated:YES];
}


//微信按钮
-(void)wxButtonAction:(UIButton *)sender
{
    UIImageView *img = (UIImageView *)[self.view viewWithTag:601];
    img.image = [UIImage imageNamed:@"pay_selectd"];
    
    UIImageView *img1 = (UIImageView *)[self.view viewWithTag:602];
    img1.image = [UIImage imageNamed:@"pay_unselectd"];
    _rowNumber = 0;

}
//支付宝按钮

-(void)aliButtonAction:(UIButton *)sender
{
    UIImageView *img = (UIImageView *)[self.view viewWithTag:601];
    img.image = [UIImage imageNamed:@"pay_unselectd"];
    
    UIImageView *img1 = (UIImageView *)[self.view viewWithTag:602];
    img1.image = [UIImage imageNamed:@"pay_selectd"];
    
    _rowNumber = 1;

}


-(void)payButtonAction
{
    
    if (!_isAgree) {
        
        [self showAlertControllerWithString:@"请先阅读并同意协议"];
        
    } else {
    
        NSString * urlString = nil;
        NSString * pathString = nil;
        if (_rowNumber == 1) {
            
            urlString = kUrlScheme;
            pathString = Order_alipay;
        }
        else{
            urlString = kUrlWX;
            pathString = Order_wx;
        }
        
        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        NSString * quoteid = [NSString stringWithFormat:@"%@",self.quoteid];
        if (quoteid.length > 0) {
            [dic setObject:self.quoteid forKey:@"quoteid"];
        }
        [dic setObject:self.orderid forKey:@"orderid"];
        if (self.isScore) {
            [dic setObject:@(1) forKey:@"score"];

        } else {
            [dic setObject:@(0) forKey:@"score"];

        }

    
    Common *com = [[Common alloc]init];
    
        [com afPostRequestWithUrlString:pathString parms:dic finishedBlock:^(id responseObj) {
            
            NSMutableDictionary * dicObj =[NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
            
            if ([dicObj[@"success"] boolValue]) {
                
                NSData * data = [NSJSONSerialization dataWithJSONObject:dicObj[@"data"] options:NSJSONWritingPrettyPrinted error:nil];
                NSString* charge = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                
                [Pingpp createPayment:charge
                       viewController:self
                         appURLScheme:urlString
                       withCompletion:^(NSString *result, PingppError *error) {
                           if ([result isEqualToString:@"success"]) {
                               //延迟执行
                               dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                                   // 支付成功
   
                                PayFinishVC *payV = [[PayFinishVC alloc]init];
                                   payV.orderN = self.orderNumber;
                                   payV.moneyS = self.moneyString;
                                   
                                   [self.navigationController pushViewController:payV animated:YES];
                                   
                                   
                               });
                               
                               
                           } else {
                               // 支付失败或取消
                               
                               [self alertControllerWith:@"支付失败"];
                               
                               NSLog(@"Error: code=%lu msg=%@", (unsigned long)error.code, [error getMsg]);
                           }
                       }];
                
            } else {
                
                [self alertControllerWith:dicObj[@"message"] andInteger:0];
                
                
            }
            
        } failedBlock:^(NSString *errorMsg) {
        }];
    }
    

}



-(void)alertControllerWith:(NSString *)string andInteger:(NSInteger)integer
{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alertC addAction:action];
    
    [self presentViewController:alertC animated:YES completion:nil];
    
    if (integer == 1) {
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [alertC dismissViewControllerAnimated:YES completion:nil];
            
            [self backAction];
            
        });
    }
    
    
}

-(void)alertControllerWith:(NSString *)string
{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:string preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"重试" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self payButtonAction];
        
    }];
       UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertC addAction:action];
    [alertC addAction:action1];
    
    [self presentViewController:alertC animated:YES completion:nil];
    
    
}



-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    
        [rootVC setTabBarHidden:YES];
    
}


-(UIButton *)backButtonWithString:(NSString *)title andFont:(NSInteger)integer andFrame:(CGRect)frame
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:YellowColor forState:UIControlStateNormal];
    button.titleLabel.font = Font(integer);
    
    return button;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)showAlertControllerWithString:(NSString *)string
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:string message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:action1];
    [alertController addAction:action2];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
